package com.xyy.saas.payment.util.mq;

import com.xyy.saas.payment.adpater.pingxx.domain.WithdrawalDO;
import com.xyy.saas.payment.callback.core.handler.WithdrawalHandler;
import com.xyy.saas.payment.common.RocketMqGroup;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.dao.mapper.WithdrawOrderMapper;
import com.xyy.saas.payment.dao.model.WithdrawOrder;
import com.xyy.saas.payment.payment.core.bo.WithdrawalBO;
import com.xyy.saas.payment.util.DateUtil;
import com.xyy.saas.payment.util.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;

/**
 * 异步提现
 */
@Service
@RocketMQMessageListener(topic = RocketMqTopic.TOPIC_WITHDRAW_NOTICE, consumerGroup = RocketMqGroup.GROUP_WITHDRAW_NOTICE, consumeMode = ConsumeMode.CONCURRENTLY)
public class WithdrawNoticeConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(WithdrawNoticeConsumer.class);

    @Autowired
    private WithdrawOrderMapper withdrawOrderMapper;
    @Autowired
    private WithdrawalHandler withdrawalHandler;

    @Override
    public void onMessage(MessageExt message) {
        String data = new String(message.getBody());
        Map<String, String> withdrawData = JSONUtils.parse2Map(data, String.class, String.class);
        LOGGER.info("WithdrawNoticeConsumer#onMessage start. withdrawData:{}", JSONUtils.toJSON(withdrawData));

        if(withdrawData == null) {
            return;
        }

        String status = withdrawData.get("status");
        String withdrawNo = withdrawData.get("withdrawNo");
        String errorMsg = withdrawData.get("errorMsg");

        try {
            WithdrawOrder withdrawOrder = withdrawOrderMapper.selectByWithdrawNo(withdrawNo);
            WithdrawalDO domain = new WithdrawalDO();
            domain.setWithdrawNo(withdrawNo);

            if(WithdrawalBO.success(status)) {
                domain.setStatus("succeeded");
                domain.setFailureMsg("交易成功");
            }
            else if(WithdrawalBO.refund(status)) {
                domain.setStatus("refund");
                domain.setFailureMsg("交易退汇");
            }
            else {
                domain.setStatus("failed");
                domain.setFailureMsg(StringUtils.isNotBlank(errorMsg) ? errorMsg : "交易失败");
            }

            domain.setFee(withdrawOrder.getFee());
            domain.setTimeSucceeded(DateUtil.now());
            domain.setId(withdrawOrder.getChannelWithdrawNo());
            domain.setExtra("");
            withdrawalHandler.callBackHandler(domain);
        }
        catch(Exception e) {
            LOGGER.error("SyncWithdrawConsumer#onMessage consumer error withdrawNo:{}", withdrawNo, e);
        }

        LOGGER.info("WithdrawNoticeConsumer#onMessage end. withdrawNo:{}", withdrawNo);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.setConsumeTimestamp(UtilAll.timeMillisToHumanString3(System.currentTimeMillis()));
    }
}